package com.openfarmanager.android;

import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.openfarmanager.android.core.Settings;
import com.openfarmanager.android.filesystem.FileSystemScanner;
import com.openfarmanager.android.utils.SystemUtils;
import com.openfarmanager.android.view.ToastNotification;

public class SettingsActivity extends PreferenceActivity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);

        findPreference("file_system_sort").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {

                showSingleChoiceDialog(R.layout.preference_list_view, getString(R.string.file_system_sort),
                        getResources().getStringArray(R.array.files_sort_array),
                        getResources().getStringArray(R.array.files_sort_array_values), App.sInstance.getSettings().getFileSortValue(),
                        new OnChooserValueSelectedListener() {
                            @Override
                            public void onValueSelected(int index) {
                                App.sInstance.getSettings().setFileSortValue(getResources().getStringArray(R.array.files_sort_array_values)[index]);
                            }
                        });
                return true;
            }
        });

        findPreference("file_system_file_info").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {

                showSingleChoiceDialog(R.layout.preference_list_view, getString(R.string.file_system_file_info),
                        getResources().getStringArray(R.array.file_info_type_array),
                        getResources().getStringArray(R.array.file_info_type_array_values), App.sInstance.getSettings().getFileInfoType(),
                        new OnChooserValueSelectedListener() {
                            @Override
                            public void onValueSelected(int index) {
                                App.sInstance.getSettings().setFileInfoTypeValue(getResources().getStringArray(R.array.file_info_type_array_values)[index]);
                            }
                        });
                return true;
            }
        });

        CheckBoxPreference multiPanels = (CheckBoxPreference) findPreference("multi_panels");
        multiPanels.setChecked(App.sInstance.getSettings().isMultiPanelMode());

        findPreference("feedback").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                sendFeedback();
                return true;
            }
        });

        findPreference("rate").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                Uri uri = Uri.parse(getString(R.string.rate_app_url));
                Intent intent = new Intent (Intent.ACTION_VIEW, uri);
                startActivity(intent);
                return true;
            }
        });

        App.sInstance.getSettings().getSharedPreferences().registerOnSharedPreferenceChangeListener(mPreferenceChangeListener);
    }

    private void showSingleChoiceDialog(int layoutId, String title, final String[] items, final String[] values,
                                        String defaultValue, final OnChooserValueSelectedListener listener) {
        View view = getLayoutInflater().inflate(layoutId, null);

        final Dialog dialog = new Dialog(SettingsActivity.this, R.style.Action_Dialog);
        dialog.setContentView(view);

        RadioGroup group = (RadioGroup) view.findViewById(R.id.items_list);
        int i = 0;
        for (String item : items) {
            RadioButton button = new RadioButton(SettingsActivity.this);
            button.setButtonDrawable(R.drawable.radio_selector);
            button.setText(item);
            group.addView(button);

            button.setId(i);

            if (values[i++].equals(defaultValue)) {
                button.setChecked(true);
            }
        }

        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                listener.onValueSelected(i);
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });

        ((TextView) view.findViewById(R.id.title)).setText(title);

        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });

        dialog.show();
        adjustDialogSize(dialog);

    }

    SharedPreferences.OnSharedPreferenceChangeListener mPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
            if ("folders_first".equals(s) || "sdcard_root".equals(s)) {
                FileSystemScanner.sInstance.initFilters();
            } else if ("multi_panels".equals(s)) {
                setResult(Main.RESULT_CODE_PANELS_MODE_CHANGED);
                SharedPreferences preferences = App.sInstance.getSettings().getSharedPreferences();
                if (!preferences.getBoolean(Settings.MULTI_PANELS_CHANGED, false)) {
                    preferences.edit().putBoolean(Settings.MULTI_PANELS_CHANGED, true).commit();
                }
            } else if ("force_en_lang".equals(s)) {
                ToastNotification.makeText(getApplicationContext(), getString(R.string.will_be_applied_after_restarts),
                        Toast.LENGTH_LONG).show();
            }
        }
    };

    private void sendFeedback() {
        Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", getString(R.string.feedback_to), null));
        String version = "";
        try {
            PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
            version = pi.versionName + "/" + pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            throw new IllegalStateException("Invalid package name", e);
        }

        String subject = getString(R.string.feedback_subject, version);
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);

        try {
            startActivity(emailIntent);
        } catch (ActivityNotFoundException anfe) {
            runOnUiThread(new Runnable() {
                public void run() {
                    if (!isFinishing())
                        Toast.makeText(SettingsActivity.this, getString(R.string.no_email_client), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    @Override
    public void onDestroy() {
        App.sInstance.getSettings().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(mPreferenceChangeListener);
        super.onDestroy();
    }

    /**
     * Adjust dialog size. Actuall for old android version only (due to absence of Holo themes).
     */
    private void adjustDialogSize(Dialog dialog) {
        if (!SystemUtils.isHoneycombOrNever()) {
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);

            WindowManager.LayoutParams params = new WindowManager.LayoutParams();
            params.copyFrom(getWindow().getAttributes());
            params.width = (int) (metrics.widthPixels * 0.8f);
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;

            dialog.getWindow().setAttributes(params);
        }
    }

    private interface OnChooserValueSelectedListener {
        void onValueSelected(int index);
    }

}
